<template>
  <div>
    <div class="inline-edit"
         v-show="isEditing"
    >
      <a-input
          v-model:value="innerValue"
          placeholder="文本不能为空"
          :class="{ 'input-error': !validateCheck}"
          size="small"
          class="ant-input"
          ref="inputRef"
          @blur="handleSubmit"
      >
      </a-input>
    </div>
    <div class="inline-edit" v-show="!isEditing" @click="handleClick">
      <span>{{innerValue}}</span>
    </div>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, nextTick, ref, watch} from 'vue'
import {CloseCircleOutlined} from "@ant-design/icons-vue";

export default defineComponent({
  name: "InlineEdit",
  components: {CloseCircleOutlined},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  emits: ['change'],
  setup (props, ctx) {
    const innerValue = ref(props.value)
    const isEditing = ref(false)
    const validateCheck = computed(() => innerValue.value.trim() !== '')
    const inputRef = ref<HTMLInputElement>()

    let cacheInnerValue = props.value
    let isEnter = false

    watch(isEditing, async (newVal) => {
      if (newVal) {
        cacheInnerValue = innerValue.value
        await nextTick()
        if (inputRef.value) {
          inputRef.value.focus()
        }
      }
    })
    const handleClick = () => {
      isEditing.value = true
    }
    const handleSubmit = () => {
      isEnter = true;
      if (validateCheck.value) {
        isEditing.value = false
        ctx.emit('change', innerValue.value)
      }
    }
    const handleEsc = () => {
      if (!isEnter) {
        isEditing.value = false
        innerValue.value = cacheInnerValue
      }
      isEnter = false
    }
    return {
      innerValue,
      isEditing,
      validateCheck,
      inputRef,
      handleClick,
      handleSubmit,
      handleEsc,
    }
  }
})
</script>

<style scoped>
.inline-edit {
  cursor: pointer;
  height: 32px;
  line-height: 32px;
}
.ant-input{
  border: 1px solid #1890ff;
}
.ant-input.input-error {
  border: 1px solid #f5222d;
}
.ant-input.input-error:focus {
  border-color:  #f5222d;
}
.ant-input.input-error::placeholder {
  color: #f5222d;
}
</style>